function gmm = gmm_train(X,y,num_components)

classes = sort(unique(y));
num_classes = size(classes, 1);
num_points = size(X, 1);

gmm.model = cell(num_classes, 1);
gmm.prior = ones(num_classes, 1);

for i = 1 : num_classes
    class = classes(i);
    Xi = X(y == class,:);
    class_size = size(Xi, 1);
    gmm.prior(i) = class_size / num_points;
    fprintf('Fitting GMM to class %d ...\n', class);
    if (num_components == 1)
        gmm.model{i} = gmm_fitml(Xi);
    else
        gmm.model{i} = gmm_fitem(Xi, num_components);
    end
    gmm.label(i) = class;
end